﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MockNetCore.Handlers
{
    public class ObjectHandler : TypeHandler
    {
        public object handle(Options options)
        {
            JObject jo = new JObject();
            JObject template = (JObject)options.template;
            List<String> keyList = template.Properties().Select(m => m.Name).ToList();
            // 'obj|min-max': {}
            if (options.rule.min != null)
            {
                keyList.Sort(delegate (string a, string b) { return (new Random()).Next(-1, 1); });
                int count = keyList.Count > options.rule.count ? options.rule.count.Value : keyList.Count;
                for (int i = 0; i < count; i++)
                {
                    String key = keyList[i >= keyList.Count ? i - keyList.Count : i];
                    String parsedKey = parseName(key);
                    jo.Add(parsedKey, JToken.FromObject(Handler.gen(template.GetValue(key).ToObject<object>(), key, options.context)));
                }

                return jo;
            }

            // 'obj': {}
            for (int i = 0; i < keyList.Count; i++)
            {
                String key = keyList[i];
                String parsedKey = parseName(key);
                jo.Add(parsedKey, JToken.FromObject(Handler.gen(template.GetValue(key).ToObject<Object>(), key, options.context)));
            }
            return jo;
        }

        private static String parseName(String name)
        {
            return name.Split(new char[] { '|' })[0];
        }

        public Type[] support()
        {
            return new Type[] { typeof(JObject) };
        }
    }
}